<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Ruby Arrays</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Arrays" />
<meta name="keywords" content="ruby arrays,ruby array class,arrays in ruby,ruby array methods" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/ruby_arrays.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Learning Ruby site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Ruby Arrays</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_blocks.html">&lt;Ruby Blocks | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_ranges.html">Ranges&gt;</a>
                  </strong>
                </p>

                <p>An <strong>Array</strong> is just a list of items in order (like mangoes, apples, and oranges). Every slot in the list acts like a variable: you can see what object a particular slot points to, and you can <i>make it point to a different object</i>. You can make an array by using square brackets In Ruby, the first value in an array has index 0. The <strong>size</strong> and <strong>length</strong> methods return the number of elements in an array. The last element of the array is at index <strong>size-1</strong>. Negative index values count from the end of the array, so the last element of an array can also be accessed with an index of -1. If you attempt to read an element beyond the end of an array (with an index >= <strong>size</strong>) or before the beginning of an array (with an index &lt; <strong>-size</strong>), Ruby simply returns <strong>nil</strong> and does not throw an exception. Ruby's arrays are mutable - arrays are dynamically resizable; you can append elements to them and they grow as needed. Let us look at the following example <strong>p018arrays.rb</strong>. Please go through the program carefully.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p018arrays.rb
                # Arrays

                # Empty array
                var1 = []
                # Array index starts from 0
                puts var1[0]

                # an array holding a single number
                var2 = [5]
                puts var2[0]

                # an array holding two strings
                var3 = ['Hello', 'Goodbye']
                puts var3[0]
                puts var3[1]

                flavour = 'mango'
                # an array whose elements are pointing
                # to three objects - a float, a string and an array
                var4 = [80.5, flavour, [true, false]]
                puts var4[2]

                # a trailing comma is ignored
                name = ['Satish', 'Talim', 'Ruby', 'Java',]
                puts name[0]
                puts name[1]
                puts name[2]
                puts name[3]
                # the next one outputs nil
                # nil is Ruby's way of saying nothing
                puts name[4]
                # we can add more elements too
                name[4] = 'Pune'
                puts name[4]
                # we can add anything!
                name[5] = 4.33
                puts name[5]
                # we can add an array to an array
                name[6] = [1, 2, 3]
                puts name[6]

                # some methods on arrays
                newarr = [45, 23, 1, 90]
                puts newarr.sort
                puts newarr.length
                puts newarr.first
                puts newarr.last

                # method each (iterator) - extracts each element into loc
                # do end is a block of code
                # we shall talk about blocks soon here -
                # /satishtalim/ruby_blocks_and_procs.html
                # variable loc refers to each item in the array as it goes through the loop
                locations = ['Pune', 'Mumbai', 'Bangalore']

                locations.each do |loc|
                  puts 'I love ' + loc + '!'
                  puts "Don't you?"
                end

                # delete an entry in the middle and shift the remaining entries
                locations.delete('Mumbai')
                locations.each do |loc|
                  puts 'I love ' + loc + '!'
                  puts "Don't you?"
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The method <strong>each</strong> (for any object) allows us to do something (whatever we want) to each object the array points to. In the example, we are able to go through each object in the array without using any numbers. Here are a few things to remember:</p>

                <ul><li>The variable loc inside the "goalposts" refers to each item in the array as it goes through the loop. You can give this any name you want, but make it memorable.</li><li>The <strong>do</strong> and <strong>end</strong> identify a block of code that will be executed for each item. Blocks are used extensively in Ruby.</li></ul>

                <p>Here's an interesting example of a method that returns an array. Example <strong>p019mtdarry.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p019mtdarry.rb
                # if you give return multiple parameters,
                # the method returns them in an array
                # The times method of the Integer class iterates block num times,
                # passing in values from zero to num-1

                def mtdarry
                  10.times do |num|
                    square = num * num
                    return num, square if num > 5
                  end
                end

                # using parallel assignment to collect the return value
                num, square = mtdarry
                puts num
                puts square
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p019mtdarry.rb
                6
                36
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The <strong>times</strong> method of the <strong>Integer</strong> class iterates block num times, passing in values from zero to num-1. As we can see, if you give <strong>return</strong> multiple parameters, the method returns them in an array. You can use parallel assignment to collect this return value.</p>

                <h3>Parallel Assignment</h3>

                <p>To explain this, we'll use the terms lvalue and rvalue. An lvalue is something that can appear on its own on the left-hand side of an assignment (a variable, constant, or <a href="/satishtalim/ruby_access_control.html">attribute setter method</a>). An rvalue is something that can appear on its own on the right hand side. Ruby lets you have a comma-separated list of rvalues. Once Ruby sees more than one rvalue in an assignment, the rules of parallel assignment come into play. First, all the rvalues evaluated, left to right, and collected into an array (unless they are already an array). This array will be the eventual value returned by the overall assignment. Next, the left hand side (lhs) is inspected. If it contains a single element, the array is assigned to that element.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                a = 1, 2, 3, 4 # => a == [1, 2, 3, 4]
                b = [1, 2, 3, 4] # => b == [1, 2, 3, 4]
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>If the lhs contains a comma, Ruby matches values on the rhs against successive elements on the lhs. Excess elements are discarded.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                a, b = 1, 2, 3, 4 # => a == 1, b == 2
                c, = 1, 2, 3, 4 # => c == 1
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <h3>Environment Variables</h3>

                <p>An environment variable is a link between our program and the outside world. An environment variable is essentially a label referring to a piece of text; and can be used to store configuration information such as paths, usernames, and so on. You can access operating system environment variables using the predefined variable <strong>ENV</strong>. <strong>ENV</strong> is simply a hash.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                ENV.each {|k,v| puts "#{k}: #{v}"}
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Ruby sets ENV to the environment variables. After that, iteration proceeds with <strong>each</strong>. This time, the block takes two parameters: k (key) and v (value). Blocks are a completely general mechanism and can take any number of arguments.</p>

                <p>The values of some environment variables are read by Ruby when it first starts. These variables modify the behavior of the interpreter, as shown below.</p>

                <p><a href="/images/env.jpg" title="Environment Variables"><img src="/images/env.jpg" alt="Environment Variables" /></a></p>

                <p>A Ruby program may write to the <strong>ENV</strong> object. On most systems this changes the values of the corresponding environment variables. However, this change is local to the process that makes it and to any subsequently spawned child processes. A subprocess changes an environment variable, and this change is inherited by a process that it then starts. However, the change is not visible to the original parent. (This just goes to prove that parents never really know what their children are doing.)</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                ENV["course"] = "FORPC101"
                puts "#{ENV['course']}"
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>As of Ruby 1.9, setting an environment variable's value to <b>nil</b> removes the variable from the environment.</p>

                <h3>Command-line arguments</h3>

                <p>If you're starting a program from the command line, you can append parameters onto the end of the command and the program processes them.<br /><br />You can do the same with your Ruby application. Ruby automatically places any parameters that are appended to the command line when you launch your Ruby program into a special array called <strong>ARGV</strong>. If your program is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                f = ARGV[0]
                puts f
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>You can execute this program from the command line as:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                ruby tmp.rb 23
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The program should display 23.</p>

                <h3>Library GetoptLong</h3>

                <p>Class <strong>GetoptLong</strong> supports command-line option parsing. Options may be a minus sign (-) followed by a single character, or two minus signs (--) followed by a name (a long option). Options may be given in any order. A single internal option may have multiple external representations. For example, the option to control verbose output could be any of -v, --verbose, or --details. Some options may also take an associated value. Each internal option is passed to <strong>GetoptLong</strong> as an array, containing strings representing the option's external forms and a flag. The flag specifies how <strong>GetoptLong</strong> is to associate an argument with the option (NO_ARGUMENT, REQUIRED_ARGUMENT, or OPTIONAL_ARGUMENT).<br /><br />Suppose I want to call a Ruby program as:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                ruby tsftpc.rb -hftp.ibiblio.org -n21 -uanonymous -ps@s.com
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Here's the code to do so:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                require 'getoptlong'

                # Call using "ruby tsftpc.rb -hftp.ibiblio.org -n21 -uanonymous -ps@s.com"
                # The parameters can be in any order
                unless ARGV.length == 4
                  puts "Usage: ruby tsftpc.rb -hftp_site_url -nport_no -uuser_name -ppassword"
                  exit
                end

                host_name = port_no = user_name = password = ''
                # specify the options we accept and initialize
                # the option parser
                opts = GetoptLong.new(
                [ "--hostname", "-h", GetoptLong::REQUIRED_ARGUMENT ],
                [ "--port", "-n", GetoptLong::REQUIRED_ARGUMENT ],
                [ "--username", "-u", GetoptLong::REQUIRED_ARGUMENT ],
                [ "--pass", "-p", GetoptLong::REQUIRED_ARGUMENT ]
                )
                # process the parsed options
                opts.each do |opt, arg|
                  case opt
                    when '--hostname'
                      host_name = arg
                    when '--port'
                      port_no = arg
                    when '--username'
                      user_name = arg
                    when '--pass'
                      password = arg
                  end
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p><strong>require</strong> gives you access to the many extensions and programming libraries bundled with the Ruby programming language-as well as an even larger number of extensions and libraries written independently by other programmers and made available for use with Ruby. We shall be studying <strong><a href="/satishtalim/including_other_files_in_ruby.html">require</a></strong> in more detail, later on. Also, later on, we shall study how to access <a href="/satishtalim/ruby_constants.html">constants</a> using <strong>::</strong></p>

                <p><b>How do I convert objects into an Array?</b> If you want to wrap objects in an <b>Array</b>, you can use a special <b>Kernel</b> module Array method (that starts with a capital letter and looks like a class). This special method converts its one argument into an array. For example:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                str = 'hello'
                print Array(str).class # Array
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Another example:</p>
                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                str = 'hello\nworld'
                print Array(str) # ["hello\\nworld"]
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p><b>What are the ancestors of Array?</b> Run the following program, to find that out:</p>
                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                a = [1,2,3,4]
                print a.class.ancestors
                </textarea>
                <!-- InstanceEndEditable -->
                </div>
                <p>You should see:</p>
                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                [Array, Enumerable, Object, Kernel, BasicObject]
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>You can refer to all the details of the <a href="http://ruby-doc.org/core-2.3.0/Array.html" >Array class here</a>.</p>

                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9-2-0">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_blocks.html">&lt;Ruby Blocks | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_ranges.html">Ranges&gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">
            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>

<!-- footer ends here -->
<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->
</body>
</html>
